package com.hifar.demo2;

import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;

public class DXJG0001AParser {
    
    public static void parseAndGenerate(String sourcePath, String dataPath, String outputPath) {
        try {
            // 解析源文件DXJG0001A.xml
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document sourceDoc = builder.parse(new File(sourcePath));
            
            // 解析数据文件DATA-DXJG0001A.xml
            Document dataDoc = builder.parse(new File(dataPath));
            
            // 处理值替换
            processBackfillValue(sourceDoc, dataDoc);
            
            // 输出新文件
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(sourceDoc);
            
            // 确保输出目录存在
            new File(outputPath).getParentFile().mkdirs();
            
            StreamResult result = new StreamResult(new File(outputPath));
            transformer.transform(source, result);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private static void processBackfillValue(Document sourceDoc, Document dataDoc) {
        NodeList backfillNodes = sourceDoc.getElementsByTagName("backfillvalue");
        for (int i = 0; i < backfillNodes.getLength(); i++) {
            Element backfillElement = (Element) backfillNodes.item(i);
            String dataId = backfillElement.getAttribute("dataID");
            
            // 从dataDoc中查找匹配dataID的data元素
            NodeList dataNodes = dataDoc.getElementsByTagName("data");
            for (int j = 0; j < dataNodes.getLength(); j++) {
                Element dataElement = (Element) dataNodes.item(j);
                if (dataId.equals(dataElement.getAttribute("dataID"))) {
                    String value = dataElement.getTextContent().trim();
                    backfillElement.setTextContent(value);
                    break;
                }
            }
        }
    }
}